package com.gmail.hh.flickrj.sample.android.images;

import java.lang.ref.SoftReference;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gmail.hh.flickrj.sample.android.tasks.LoadImageTask;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;

@SuppressLint("NewApi")
public final class ImageCache {
	
	private static final Logger logger = LoggerFactory.getLogger(ImageCache.class);

	private static final Map<String, SoftReference<Bitmap>> cache = new LinkedHashMap<String, SoftReference<Bitmap>>() {
		private static final long serialVersionUID = 1L;

		/* (non-Javadoc)
		 * @see java.util.LinkedHashMap#removeEldestEntry(java.util.Map.Entry)
		 */
		@Override
		protected boolean removeEldestEntry(
				Entry<String, SoftReference<Bitmap>> eldest) {
		//	logger.error("ImageCache - removeEldestEntry- size: " +size() );
			return size() > 50;
		}

	};

	private static final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
	private static final Lock read  = readWriteLock.readLock();
	private static final Lock write = readWriteLock.writeLock();

	/**
	 * 
	 */
	private ImageCache() {
		super();
	}

	public static Bitmap getFromCache(String id){
	//	logger.error("ImageCache - get: " + id);
	//	protokoll();
		read.lock();
		try {
			if(!cache.containsKey(id))
				return null;
			SoftReference<Bitmap> ref=cache.get(id);
			return ref.get();
		} finally {
			read.unlock();
		}
	}

	public static void saveToCache(String id, Bitmap bitmap){
		write.lock();
		try {
			cache.put(id, new SoftReference<Bitmap>(bitmap));
		} finally {
			write.unlock();
		}
	//	logger.error("ImageCache - saveto: " + id);
	//	protokoll();
	}

	public static void clear() {
		logger.error("ImageCache - clear: " );
		write.lock();
		try {
			cache.clear();
		} finally {
			write.unlock();
		}
	}

	public static void protokoll() {
		logger.error("ImageCache - size: " + cache.size() );
		Set<String> keys = cache.keySet();
		int i=0;
		for (String key : keys ){
			i++;
			SoftReference<Bitmap> value = cache.get(key);
			Bitmap image = value.get();
			String state = "null";
			if (image!=null ){
				state = "OK  Size:" + image.getByteCount();
			} 
			String url = key.substring(key.length()-20, key.length()-1 );
			logger.error("  " + i + "  " + url + "  "  + state);
		} 
	}

}
